#pragma once

#include <cstdlib>
#include <cstring>

#include <iostream>
#include <string>
#include <functional>

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#include <unistd.h>
#include <sys/wait.h>
#include <pthread.h>

#include "Log.hpp"
#include "InetAddr.hpp"
#include "Socket.hpp"

using namespace std;

using io_service_t=function<void(socket_sptr,InetAddr)>;

// 多线程传递的参数
class TcpServer;
class ThreadData
{
public:
    ThreadData(socket_sptr fd, InetAddr client, TcpServer *s)
        :sockfd(fd), clientaddr(client), self(s)
    {
    }

public:
    socket_sptr sockfd;
    InetAddr clientaddr;
    TcpServer *self;
};

class TcpServer
{
public:
    TcpServer(uint16_t port,io_service_t service)
        : _localaddr("0", port), _listensock(new TcpSocket()), _isrunning(false),_service(service)
    {
        _listensock->BuildListenSocket(_localaddr);
    }



    static void *HandlerSock(void *args)
    {
        pthread_detach(pthread_self());
        ThreadData *td = static_cast<ThreadData *>(args);
        td->self->_service(td->sockfd, td->clientaddr);
        ::close(td->sockfd->SockFd());
        delete td;
        return nullptr;
    }

    void Loop()
    {
        _isrunning = true;
        while (_isrunning)
        {
            InetAddr peeraddr;
            socket_sptr sock = _listensock->Accepter(&peeraddr);

            // 解决方案2:多线程---version2
            pthread_t tid;
            ThreadData *td = new ThreadData(sock, peeraddr, this);
            pthread_create(&tid, nullptr, HandlerSock, td);
        }
        _isrunning = false;
    }

    ~TcpServer()
    {
      
    }

private:
    InetAddr _localaddr;
    unique_ptr<Socket> _listensock;
    bool _isrunning;

    io_service_t _service;
};